package cn.xerllent.common.rest;

import java.time.LocalDateTime;
import java.util.Map;
import java.util.Set;

import org.springframework.data.domain.Pageable;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import cn.xerllent.common.annotation.Log;
import cn.xerllent.common.entity.MsgUser;
import cn.xerllent.common.entity.vo.ResultData;
import cn.xerllent.common.service.MsgService;
import cn.xerllent.common.service.MsgUserService;
import cn.xerllent.common.service.dto.MsgFilter;
import cn.xerllent.common.utils.SecurityUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

@RestController
@Api(tags = "通用：消息管理")
@RequestMapping("/api/msg")
public class MsgController {

    private final MsgService msgService;
    private final MsgUserService msgUserService;

    public MsgController(MsgService msgService,MsgUserService msgUserService) {
        this.msgService = msgService;
        this.msgUserService = msgUserService;
    }

    @Log("查询我的消息数据")
    @ApiOperation("查询我的消息数据,phase=0发送,1接收")
    @GetMapping
    public ResponseEntity<Object> getMyMsgs(MsgFilter filter, Pageable pageable) {
    	Long uId = SecurityUtils.getUserId();
    	filter.setUId(uId);

    	Map<String, Object>  result = msgService.queryAll(filter, pageable);
    	return new ResponseEntity<>(ResultData.data(result), HttpStatus.OK);
    }

    @Log("删除消息")
    @ApiOperation("删除消息")
    @DeleteMapping
    public ResponseEntity<Object> delete(@RequestBody Set<Integer> msgUserIds) {
    	Long uId = SecurityUtils.getUserId();
    	msgUserService.lambdaUpdate().set(MsgUser::getDel, true).eq(MsgUser::getUId, uId).in(MsgUser::getId, msgUserIds).update();
        return new ResponseEntity<>(HttpStatus.OK);
    }

    @Log("设置已读消息")
    @ApiOperation("设置已读消息")
    @PutMapping
    public ResponseEntity<Object> readed(@RequestBody Set<Integer> msgUserIds) {
    	Long uId = SecurityUtils.getUserId();
    	msgUserService.lambdaUpdate().set(MsgUser::getReaded, true).set(MsgUser::getRecvtime, LocalDateTime.now()).eq(MsgUser::getUId, uId).in(MsgUser::getId, msgUserIds).update();
        return new ResponseEntity<>(HttpStatus.OK);
    }
}
